//
//  SearchViewController.m
//  ErWa
//
//  Created by 李雪 on 16/3/14.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "NewNestHeader.h"

@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchBar *mySearchBar;/**< 搜索栏 */
@property (nonatomic, retain) NSString *highlightStr;/**< 保存搜索信息 高亮字符串 */
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) UITableView *tableview;
@property (nonatomic, assign) NSInteger number;/**< 上拉加载的变化值 */
@property (nonatomic, retain) UIImageView *imageView;/**< 背景图片 */

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化视图
    [self createSubviews];
    // 初始化变化值
    self.number = 5;
    //上拉加载
//    [self refresh];

}

///初始化视图
- (void)createSubviews
{
    UIBarButtonItem *backButon = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backButon;
    
    UIApplication *app = [UIApplication sharedApplication];
    [app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    //初始化搜索栏
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 41)];
    //签代理
    _mySearchBar.delegate = self;
    
    //下面可以改变搜索栏的背景颜色
    //    UIView *segment = [_mySearchBar.subviews objectAtIndex:0];
    //    [segment removeFromSuperview];
    //    _mySearchBar.backgroundColor = [UIColor yellowColor];
    
    
    //设置选中searchBar时的键盘最下方的类型
    //    UITextField *searchField = [[_mySearchBar subviews] lastObject];
    //    [searchField setReturnKeyType:UIReturnKeyDone];
    //搜索栏的设置
    //    _mySearchBar.tintColor = [UIColor cyanColor];
    _mySearchBar.barStyle = UIBarStyleDefault;
    _mySearchBar.keyboardType = UIKeyboardAppearanceDefault;
    _mySearchBar.placeholder = @"请输入关键字";
    
    // 设置是否显示搜索结果按钮
    [_mySearchBar setShowsSearchResultsButton:YES];
    
    self.navigationItem.titleView = _mySearchBar;
    
    [self tableviewCreate];
    //背景图片
    [self backImg];
}

- (void)tableviewCreate
{
    //初始化tableview
    self.tableview = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableview.backgroundColor = [UIColor clearColor];
    [_tableview registerClass:[DiaryCell class] forCellReuseIdentifier:@"diaryCell"];
    [_tableview registerClass:[DiaryNoPhotoCell class] forCellReuseIdentifier:@"diaryNoPhotoCell"];
    [self.view addSubview:_tableview];
}

- (void)backImg
{
    //背景图片
    self.imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_imageView];
//    _imageView.image = [UIImage imageNamed:@"collectionBack.jpg"];
    
    //显示当前没有收藏
    UILabel *tips = [UILabel new];
    [self.imageView addSubview:tips];
    tips.frame = CGRectMake(self.view.frame.size.width / 4, self.view.frame.size.height / 5 * 3, self.view.frame.size.width / 2, self.view.frame.size.height / 5);
    tips.text = @"当前没有搜索结果";
    tips.textAlignment = NSTextAlignmentCenter;
    tips.numberOfLines = 0;
    tips.font = [UIFont systemFontOfSize:20];
}

/// 设置在选中搜索栏的时候,键盘自动调用加载到界面
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //显示取消按钮
    [_mySearchBar setShowsCancelButton:YES animated:YES];
    NSLog(@"开始编辑");
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

/// 搜索栏的取消按钮按下时,执行的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [_mySearchBar resignFirstResponder];
    [_mySearchBar setShowsCancelButton:NO animated:YES];
}

/// 键盘中搜索按钮被按下时执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"搜索啦");
    
     [self dataHandler];
    [_mySearchBar resignFirstResponder];
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息 显示的文本
    self.highlightStr = searchBar.text;
   
    
}

/// 当搜索内容发生变化时,执行方法 可以实现实时搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息 显示的文本
    self.highlightStr = searchText;
    [self dataHandler];
    
}

/// 数据处理
- (void)dataHandler
{
    //如果输入的字符串为空
    if ([_highlightStr isEqualToString:@""]) {
        //如果已经存在tableview就交换位置
        //        if (_tableview) {
        [self.view bringSubviewToFront:_imageView];
        _imageView.userInteractionEnabled = NO;
        //        }
    }
//    //判断字符串里面是不是有空格
//    NSRange range = [_highlightStr rangeOfString:@" "];
//    if (range.location != NSNotFound) {
//        
//        // 判断如果有空格不执行
//        // 没有执行以下程序
//        //不写这个判断 打空格就会崩溃
//        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"当前搜索没有结果!" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alert show];
//        [alert dismissWithClickedButtonIndex:0 animated:YES];
//        NSLog(@"空格");
//    }else {
//        
        //中文转码
        NSString *urlStr = [_highlightStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_highlightStr]];
        NSLog(@"%@", urlStr);
        //将变化的参数进行拼接出一个新的网址
        NSString *newUrlStr = [NSString stringWithFormat:@"http://api.wsq.umeng.com/v2/feed/search?os=iOS&openudid=ab2665bf1689f98c2225a0fdbd3c01b8ed54b61c&sdkv=2.2.1&ak=5636cff167e58ef91b0001ae&de=iPhone5,4&mac=02:00:00:00:00:00&uid=56a330927019c97215dad1ed&keywords=%@&count=5", urlStr];
        // 解析数据
        
//        [[AFHTTPSessionManager manager] GET:newUrlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSLog(@"搜索数据解析成功");
//            self.dataArr = [DiaryModal modelHanderWithArray:responseObject[@"items"]];
//            NSLog(@"%ld", (unsigned long)_dataArr.count);
//            
//            [_tableview reloadData];
//            
//            if (_dataArr.count != 0) {
//                [self.view bringSubviewToFront:_tableview];
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"搜索数据解析失败");
//        }];
        
        [AFNetworking GETWithURL:newUrlStr completion:^(id result) {
            self.dataArr = [DiaryModal modelHanderWithArray:result[@"items"]];
            
            [_tableview reloadData];
            if (_dataArr.count != 0) {
                [self.view bringSubviewToFront:_tableview];
            }
        }];
//    }
}

//当视图滚动时 关闭键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.mySearchBar resignFirstResponder];
    
}
//视图已经出现时 弹出键盘
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
        self.mySearchBar.text = @"";
    [self.mySearchBar becomeFirstResponder];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _dataArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArr.count != 0) {
        DiaryModal *modal = _dataArr[indexPath.row];
        
        
        
        
        if (modal.backImgUrl == nil) {
            DiaryNoPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"diaryNoPhotoCell" forIndexPath:indexPath];
            //消除点击后的灰色
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            //高亮设置
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:modal.content];
            //取范围
            NSRange range = [modal.content rangeOfString:_highlightStr];
            [attStr setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
            cell.contentLabel.attributedText = attStr;
            
            cell.userNameLabel.text = modal.name;
            //            cell.contentLabel.text = modal.content;
            [cell.userImgview sd_setImageWithURL:[NSURL URLWithString:modal.imgUrl] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
            
            
            
            //取消点击cell变灰
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            //     判断当前是什么模式
            BOOL model = [AccountManager sharedInstance].isNight;
            if (model == YES) {
                cell.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
            } else {
                cell.backgroundColor = [UIColor clearColor];
            }
            
            
            return cell;
        }else {
            DiaryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"diaryCell" forIndexPath:indexPath];
            
            //高亮设置
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:modal.content];
            //取范围
            NSRange range = [modal.content rangeOfString:_highlightStr];
            [attStr setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
            cell.contentLabel.attributedText = attStr;
            
            cell.userNameLabel.text = modal.name;
            //            cell.contentLabel.text = modal.content;
            [cell.imgView sd_setImageWithURL:[NSURL URLWithString:modal.backImgUrl] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
            [cell.userImgview sd_setImageWithURL:[NSURL URLWithString:modal.imgUrl] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
            
            
            
            
            
            //取消点击cell变灰
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            //     判断当前是什么模式
            BOOL model = [AccountManager sharedInstance].isNight;
            if (model == YES) {
                cell.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
            } else {
                cell.backgroundColor = [UIColor clearColor];
            }
            
            return cell;
        }
    }else {
        
        return 0;
    }
    
    
    
}

/// 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DiaryModal *modal = _dataArr[indexPath.row];
    if (modal.backImgUrl == nil) {
        return [UIScreen mainScreen].bounds.size.height / 5;
    }else {
        return [UIScreen mainScreen].bounds.size.height / 2;
    }
}


/// 返回按钮的实现
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

/// 点击cell进入详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DiaryDetailPageVC *detailVC = [[DiaryDetailPageVC alloc] init];
    detailVC.modal = _dataArr[indexPath.row];
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

//// 上拉加载
- (void)refresh
{
    
    //上拉加载
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //如果数据字典不为空 那么就刷新请求新的数据
    if (_dataArr.count != 0) {
        [self.tableview.mj_footer beginRefreshing];
    }
}

/// 上拉加载调用的方法
- (void)loadNewData
{
    if (![_mySearchBar.text isEqualToString:@""]) {
        
//        [MBProgressHUDManager showHUDtoView:self.view string:@"很努力的加载捏~~"];
        NSString *firstStr = @"http://api.wsq.umeng.com/v2/feed/search?start=";
        NSString *secondStr = @"&count=5&keywords=%E6%88%91&os=iOS&openudid=ab2665bf1689f98c2225a0fdbd3c01b8ed54b61c&sdkv=2.2.1&ak=5636cff167e58ef91b0001ae&de=iPhone5,4&mac=02:00:00:00:00:00&uid=56a330927019c97215dad1ed";
        NSString *urlStr = [NSString stringWithFormat:@"%@%ld%@",firstStr, (long)_number, secondStr];
//        [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSLog(@"加载成功");
//            // 创建新数组用以接收新的数据
//            NSArray *newDataArr = [NSArray array];
//            newDataArr = [DiaryModal modelHanderWithArray:responseObject[@"items"]];
//            NSLog(@"%@", newDataArr);
//            //将新的数据依次加入保存数据的数组里面
//            for (NSInteger i = 0; i < newDataArr.count; i++) {
//                [_dataArr addObject:newDataArr[i]];
//            }
//            // 刷新tableView
//            [self.tableview reloadData];
//            
//            [MBProgressHUDManager removeHUD];
//            
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"攻略加载失败");
//        }];
        [AFNetworking GETWithURL:urlStr completion:^(id result) {
            NSArray *newDataArr = [NSArray array];
            newDataArr = [DiaryModal modelHanderWithArray:result[@"items"]];
            for (NSInteger i = 0; i < newDataArr.count; i++) {
                [_dataArr addObject:newDataArr[i]];
            }
            [self.tableview reloadData];
        }];
        
        //结束刷新
        [self.tableview.mj_footer endRefreshing];
        //动态数值加5
        self.number += 5;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
